package cn.trip.auth.controller;

import cn.itrip.beans.dto.Dto;
import cn.itrip.beans.pojo.ItripUser;
import cn.itrip.common.Md5Util;
import cn.trip.auth.service.ItripUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Api(value = "Login|用户登陆、退出的控制器")
@Controller
@RequestMapping("/api")
public class LoginController {
    @Autowired
    private ItripUserService itripUserService;
    @Autowired
    Md5Util md5Util;

    /**
     * 用户登陆处理
     * 用户登录，登陆成功将所有的相关查询信息放到session和redis缓存中，下次查询直接从缓存中获取
     *
     * @param name     用户名
     * @param password 密码
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/dologin", method = RequestMethod.POST, produces = "application/json")
    @ApiOperation(value = "根据账号、密码登陆", notes = "要输入账号和密码，成功后将结果放置在session中，session名和账号相同", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "name", value = "账号", required = true),
            @ApiImplicitParam(paramType = "query", name = "password", value = "密码", required = true),
    })
    public Dto<ItripUser> dologin(@RequestParam(value = "name") String name,
                                  @RequestParam(value = "password") String password,
                                  HttpServletRequest request) {
        String token = request.getHeader("token");
        ItripUser user = new ItripUser();
        user.setUserCode(name);
        user.setUserPassword(md5Util.encode(password));
        Dto dto = itripUserService.selectByUserCode(user, token);
        return dto;
    }


    /**
     * 用户注销处理
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/logout", method = RequestMethod.GET, headers = "token", produces = "application/json")
    @ApiOperation(value = "根据用户传输的用户id清除session", notes = "需要传输一个用户账号", produces = "application/json")
    public Dto loginOut(HttpServletRequest request) {
        String token = request.getHeader("token");
        Dto dto = itripUserService.loginOut(token);
        return dto;
    }


    @ResponseBody
    @RequestMapping(value = "/retoken", method = RequestMethod.POST, headers = "token", produces = "application/json")
    @ApiOperation(value = "根据用户token重新登陆", notes = "需要传输一个用户账号", produces = "application/json")
    public Dto reToken(HttpServletRequest request) {
        String token = request.getHeader("token");
        Dto dto = itripUserService.retoken(token);
        return dto;
    }

}
